<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/8 0008
 * Time: 下午 12:02
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Session;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\TimeModel;

class TimeController extends Controller
{
    public function index()
    {
        //
        $data['data'] = TimeModel::paginate(10);
        $data['type']=3 ;
        return view('custom.timelist',compact('data'));
    }

    public function add(Request $request){

        if ($request->isMethod('get')){

            return view('custom.timeadd');
        }else{
            $data = $request->except(['_token','uploadfile']);
            $validator = Validator::make($data, [
                'time'     => 'required|string',
            ]);
            if ($validator->fails()) {
                return redirect('/admin/time/add')
                    ->withErrors($validator)
                    ->withInput($data);
            }

            TimeModel::create($data);
            return redirect('/admin/time/index');
        }
        //dd($request->all());
    }

    public function edit(Request $request,$id)
    {
        if ($request->isMethod('get')){
            $data = TimeModel::where(['id' => $id])->first()->toArray();
            return view('custom.timeedit', compact('data'));
        }else{
            $data = $request->except(['_token','uploadfile']);
            $validator = Validator::make($data, [
                'time'     => 'required|string',
            ]);
            if ($validator->fails()) {
                return redirect('/admin/time/edit')
                    ->withErrors($validator)
                    ->withInput($data);
            }
            TimeModel::where(['id'=>$id])->update($data);
            return redirect('/admin/time/index');
        }


    }

    public function postedit(Request $request)
    {
        $data = $request->except(['_token','uploadfile']);
        $validator = Validator::make($data, [
            'time'     => 'required|string',
        ]);
        if ($validator->fails()) {
            return redirect('/admin/time/edit/'.$data['id'])
                ->withErrors($validator)
                ->withInput($data);
        }
        TimeModel::where(['id'=>$data['id']])->update($data);
        return redirect('/admin/time/index');

    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $res = TimeModel::where(['id'=>$id])->first();
        if(!empty($res)) {
            TimeModel::where(['id'=>$id])->delete();
            return response()->json(['status' => 200, 'msg' =>'删除成功']);
        }
        return response()->json(['status' => 500, 'msg' =>'删除失败']);

    }



}